<template>
  <div class="page-container">
    <el-card class="content-container">
      <div class="toolbar">
        <div class="toolbar-left">
          <h3>商家管理</h3>
        </div>
        <div class="toolbar-right">
          <el-button type="danger" :disabled="selectedRows.length===0" @click="handleBatchDelete" style="margin-right: 10px;">
            批量删除
          </el-button>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增商家
          </el-button>
        </div>
      </div>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" class="search-form" inline>
        <el-form-item label="商家名称">
          <el-input v-model="searchForm.shangjiaName" placeholder="请输入商家名称" clearable />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="searchForm.shangjiaPhone" placeholder="请输入联系方式" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="(rows)=>selectedRows=rows"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="账号" />
        <el-table-column prop="shangjiaName" label="商家名称" />
        <el-table-column prop="shangjiaPhone" label="联系方式" />
        <el-table-column prop="shangjiaEmail" label="邮箱" />
        <el-table-column prop="createTime" label="注册时间" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增/编辑对话框 -->
      <el-dialog v-model="dialog.visible" :title="dialog.title" width="520px" @close="handleDialogClose">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
          <el-form-item label="账号" prop="username">
            <el-input v-model="form.username" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="商家名称" prop="shangjiaName">
            <el-input v-model="form.shangjiaName" placeholder="请输入商家名称" />
          </el-form-item>
          <el-form-item label="联系方式" prop="shangjiaPhone">
            <el-input v-model="form.shangjiaPhone" placeholder="请输入联系方式" />
          </el-form-item>
          <el-form-item label="邮箱" prop="shangjiaEmail">
            <el-input v-model="form.shangjiaEmail" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item v-if="!dialog.isEdit" label="密码" prop="password">
            <el-input v-model="form.password" placeholder="请输入初始密码" show-password />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="正常" inactive-text="禁用" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialog.visible=false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 分页 -->
      <el-pagination
        :current-page="pagination.page"
        :page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right;"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const http = proxy.$http

// 响应式数据
const loading = ref(false)
const tableData = ref([])
let selectedRows = ref([])

// 新增/编辑 对话框与表单
const dialog = reactive({ visible: false, isEdit: false, title: '新增商家' })
const formRef = ref()
const form = reactive({ id: null, username: '', shangjiaName: '', shangjiaPhone: '', shangjiaEmail: '', password: '', status: 1 })
const rules = {
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  shangjiaName: [{ required: true, message: '请输入商家名称', trigger: 'blur' }],
  shangjiaPhone: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  shangjiaEmail: [{ type: 'email', message: '邮箱格式不正确', trigger: 'blur' }],
  password: [{ required: !dialog.isEdit, message: '请输入密码', trigger: 'blur' }]
}

const searchForm = reactive({
  shangjiaName: '',
  shangjiaPhone: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 方法
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.size,
      ...searchForm
    }

    const res = await http({
      url: '/shangjia/page',
      method: 'get',
      params
    })

    if (res.code === 0) {
      tableData.value = res.data.list || []
      pagination.total = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '加载商家数据失败')
    }
  } catch (e) {
    console.error('加载商家数据失败', e)
    ElMessage.error('加载商家数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

const handleBatchDelete = async () => {
  if (!selectedRows.value || selectedRows.value.length === 0) return
  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedRows.value.length} 条商家记录吗？`,
      '批量删除',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    const ids = selectedRows.value.map(r => r.id)
    const res = await http({ url: '/shangjia/delete', method: 'post', data: { ids } })
    if (res.code === 0) {
      ElMessage.success('批量删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '批量删除失败')
    }
  } catch (e) {
    if (e !== 'cancel') {
      console.error('批量删除失败', e)
      ElMessage.error('批量删除失败')
    }
  }
}

const handleDialogClose = () => {
  formRef.value && formRef.value.clearValidate()
}

const handleAdd = () => {
  dialog.title = '新增商家'
  dialog.isEdit = false
  Object.assign(form, { id: null, username: '', shangjiaName: '', shangjiaPhone: '', shangjiaEmail: '', password: '', status: 1 })
  dialog.visible = true
}

const handleEdit = (row) => {
  dialog.title = '编辑商家'
  dialog.isEdit = true
  Object.assign(form, { ...row, password: '' })
  dialog.visible = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  try {
    const api = dialog.isEdit ? '/shangjia/update' : '/shangjia/save'
    const payload = { ...form }
    if (!dialog.isEdit) {
      if (!payload.password) {
        ElMessage.warning('请输入初始密码')
        return
      }
    } else {
      if (!payload.password) delete payload.password
    }
    const res = await http({ url: api, method: 'post', data: payload })
    if (res.code === 0) {
      ElMessage.success(dialog.isEdit ? '更新成功' : '新增成功')
      dialog.visible = false
      loadData()
    } else {
      ElMessage.error(res.msg || '提交失败')
    }
  } catch (e) {
    console.error('提交失败', e)
    ElMessage.error('提交失败')
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商家"${row.shangjiaName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const res = await http({
      url: '/shangjia/delete',
      method: 'post',
      data: { ids: [row.id] }
    })

    if (res.code === 0) {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (e) {
    if (e !== 'cancel') {
      console.error('删除商家失败', e)
      ElMessage.error('删除失败')
    }
  }
}

const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
@import '@/styles/index.scss';
</style>
